// PicCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "RefreeRetrieval.h"
#include "PicCtrl.h"

const CString CPicCtrl::CLASSNAME = L"CPicCtrl";
// CPicCtrl

IMPLEMENT_DYNAMIC(CPicCtrl, CWnd)

BEGIN_MESSAGE_MAP(CPicCtrl, CWnd)
	ON_WM_ERASEBKGND()
	ON_WM_PAINT()
END_MESSAGE_MAP()

/*==========================================================================*/

/*==========================================================================*/

CPicCtrl::CPicCtrl()
: m_bmp(NULL)
{
	RegisterWindowClass();
}

CPicCtrl::~CPicCtrl()
{
	if(m_bmp)
		::DeleteObject(m_bmp);
}

BOOL CPicCtrl::RegisterWindowClass()
{
	WNDCLASS wndcls;
	HINSTANCE hInst = AfxGetInstanceHandle();

	if (!(::GetClassInfo(hInst, CLASSNAME, &wndcls)))
	{
		// otherwise we need to register a new class

		wndcls.style            = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
		wndcls.lpfnWndProc      = ::DefWindowProc;
		wndcls.cbClsExtra       = wndcls.cbWndExtra = 0;
		wndcls.hInstance        = hInst;
		wndcls.hIcon            = NULL;
		wndcls.hCursor          = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
		wndcls.hbrBackground    = ::GetSysColorBrush(WHITE_BRUSH); // (HBRUSH) (COLOR_3DFACE + 1);
		wndcls.lpszMenuName     = NULL;
		wndcls.lpszClassName    = CLASSNAME;

		if (!AfxRegisterClass(&wndcls))
		{
			AfxThrowResourceException();
			return FALSE;
		}
	}

	return TRUE;
}

HBITMAP CPicCtrl::SetBitmap(HBITMAP hBmp)
{
	HBITMAP bmpOld = m_bmp;
	m_bmp = hBmp;

	BITMAP bmp;
	if(GetObject(hBmp, sizeof(BITMAP), &bmp))
	{
		m_szBmp.cx = bmp.bmWidth;
		m_szBmp.cy = bmp.bmHeight;
	}
	if(GetSafeHwnd())
		Invalidate();
	return bmpOld;
}

/*==========================================================================*/
// CPicCtrl message handlers
/*==========================================================================*/

BOOL CPicCtrl::OnEraseBkgnd(CDC* pDC)
{
	return TRUE;
}

void CPicCtrl::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	CRect rcClient;

	HDC hDCDevice = dc.GetSafeHdc();
	GetClientRect(&rcClient);

	if(m_bmp)
	{
		HDC hDCSrc = ::CreateCompatibleDC(hDCDevice);
		HBITMAP hBmpOld = (HBITMAP)::SelectObject(hDCSrc, m_bmp);

		::StretchBlt(hDCDevice, 0, 0, rcClient.Width(), rcClient.Height(),
			hDCSrc, 0, 0, m_szBmp.cx, m_szBmp.cy, SRCCOPY);
		//::BitBlt(hDCDevice, 0, 0, rcClient.Width(), rcClient.Height(),
		//	hDCSrc, 0, 0, SRCCOPY);

		::SelectObject(hDCSrc, hBmpOld);
		::DeleteDC(hDCSrc);
	}
	else
	{
		dc.FillSolidRect(rcClient, RGB(0, 0, 0));
	}
}
